<html>
<head>
<title>Hyves Chrome Photo Uploader</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/sha1.js"></script>
<script type="text/javascript" src="js/hyves.js"></script>
<script type="text/javascript" src="js/cake.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="js/footer.js"></script>
<script type="text/javascript">

var albumid_temp = '';

var showAnimation = function () {

	canvas = new Canvas($('#canvas_wrapper')[0], window.innerWidth, window.innerHeight);

	var circle = new Circle(100, {
		x: canvas.width / 2,
		y: canvas.height / 2,
		stroke: '#eee',
		strokeWidth: 20,
		endAngle: Math.PI*1.8
	});
	
	circle.animateTo('scale', 2, 1000, 'sine');
	circle.addFrameListener(function(t, dt) {
		this.rotation = t / 500;
	});
	
	var uploading = new ElementNode(E('h2', 'Uploading image...'), {
		fontFamily: 'Arial, Sans-serif', noScaling: true, color: 'black'
	});
	
	uploading.align = uploading.valign = 'center';
	
	circle.append(uploading);
	canvas.append(circle);
}

var loadImageFromBinaryString = function (text, ext) {	
	// write the bytes of the string to an ArrayBuffer
	var ab = new ArrayBuffer(text.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < text.length; i++) {
		ia[i] = text.charCodeAt(i);
	}
	// write the ArrayBuffer to a blob, and you're done
	if (window.BlobBuilder) { 
		// Chrome 9, 10, 11 
		var bb = new BlobBuilder();
	} else if (window.WebKitBlobBuilder) { 
		var bb = new WebKitBlobBuilder();
	} 
	bb.append(ab);
	
	// get mimeType from extention
	mimeString = 'image/' + ext;
	
	return bb.getBlob(mimeString);
};

var loadImageFromURL = function (url) {
	var req = new XMLHttpRequest();
	req.open('GET', url, false);
	//XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
	req.overrideMimeType('text/plain; charset=x-user-defined');
	req.asBlob = true;
	req.send(null);
	if (req.status != 200) return '';
	
	var aUrlParts = url.split('.');
	var ext = aUrlParts[aUrlParts.length - 1]
	
	return loadImageFromBinaryString(req.responseText, ext);
}

var fetchUploadToken = function () {
	hyves.call('media.getUploadToken', function(response) {
		uploadImage(response.get('ip'), response.get('token'));
	});
};

var uploadImage = function (ip, token) {
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "http://" + ip + "/upload?token=" + escape(token));
	xhr.send(formData);
	setTimeout('checkStatus("' + ip + '", "' + token + '")', 2000);
};

var checkStatus = function(ip, token) {
	$.getJSON("http://" + ip + "/status?token=" + escape(token), function(data) {
		if (data.data[token][0].currentstate != "done") {
			setTimeout('checkStatus("' + ip + '", "' + token + '")', 2000);
		} else {
			getImageData(data, token);
		}
	});
};

var getImageData = function (data, token) {
	mediaid = data.data[token][0].done.mediaid;
	if (localStorage["hyves_default_albumid"] && localStorage["hyves_default_albumid"] != 0) {
		hyves.call('albums.addMedia', {'albumid': localStorage["hyves_default_albumid"], 'mediaid': mediaid}, function(response) {
			chrome.tabs.getCurrent(function(tab) {
				chrome.tabs.remove(tab.id, function() {
					chrome.tabs.update(parseInt(params['tabId']), {selected:true});
				});
			});
		});
		return true;
	} else if (albumid_temp != undefined && albumid_temp != 0) {
		hyves.call('albums.addMedia', {'albumid': albumid_temp, 'mediaid': mediaid}, function(response) {
			chrome.tabs.getCurrent(function(tab) {
				chrome.tabs.remove(tab.id, function() {
					chrome.tabs.update(parseInt(params['tabId']), {selected:true});
				});
			});
		});
		localStorage['hyves_album_temp'] = 0;
		return true;
	}
	getAlbums();
	hyves.setFancyLayout(false);
	hyves.call('media.get', {'mediaid': mediaid, 'ha_responsefields': 'fancylayouttag'}, function(response) {
		// set status
		var media = response.get('media')[0];
		$("#canvas_wrapper").remove();
		$('title').text('Upload done');
		$('#wrapper_photo_upload').show();
		$('#page').show();
		$('#uploaded_image').append('<a href="' + media.url + '" target="_blank"><img src="' + media.square_extralarge.src + '" alt="" /></a>');
		$('#field_fltag').val(media.icon_extralarge.fancylayouttag);
		$('#field_name').val(media.title);
		getAlbums();
	});
};

var refreshcontextmenu = function () {
		chrome.extension.connect().postMessage({
			"name": "refresh_contextmenu"
		});
}

var getAlbums = function () {
	hyves.call('users.getLoggedin', {'ha_responsefields': 'profilepicture'}, function(responseUser) {
		hyves.call('albums.getByUser', {'userid': responseUser.get('user', 0, 'userid'),'ha_resultsperpage': 100}, function(responseA) {
			var html = '';
			for(i = 0; i < responseA.countResults('album'); i++) {
				var album_data = responseA.get('album')[i];
				html += '<li id="album_' + album_data.albumid + '">' + 
						'<button onclick="addToAlbum(this, \'' + album_data.albumid + '\');">Voeg toe</button>' + 
						'<span class="album_name">' + album_data.title + ' (<span class="mediacount">' + albumnames[album_data.visibility] + '</span>)</span>' + 
						'</li>';
			}
			localStorage["hyves_albums"] = JSON.stringify(responseA._response);
			refreshcontextmenu();
			$('#list_album').append(html);
		});
	});
};

var addToAlbum = function (e, albumid) {
	hyves.call('albums.addMedia', {'albumid': albumid, 'mediaid': mediaid}, function(response) {
		$(e).replaceWith('<span class="success">toegevoegd aan album</span>');
	});
}

$(document).ready(function() {
	showAnimation();

	params = parseQueryString(location.search);
	if (params["fileFromBackgroundPage"]) {
		fileAsText = chrome.extension.getBackgroundPage().fileAsText;
		fileExt = chrome.extension.getBackgroundPage().fileExt;
		var image = loadImageFromBinaryString(fileAsText, fileExt);
		//var image = fileAsText;
	} else {
		var image = loadImageFromURL(params["image"]);
		var temp_title = params["title"].replace(/\+/g, ' ');
		temp_title = temp_title.substr(0, temp_title.lastIndexOf('.')) || temp_title;
		params["title"] = temp_title;
	}
	formData = new FormData();
	formData.append("file", image);
	formData.append("title", params["title"]);
	albumid_temp = params["albumid"];
	
	hyves =  new Hyves(hyves_api_key, hyves_api_secret);
	hyves.restoreToken(methods, 'media.getUploadToken', fetchUploadToken, function() {
		hyves.requestAuthorizationRedirect(
			location.href, methods, 'infinite',
			function() {
				hyves.saveToken();
				fetchUploadToken();
			},
			function(e) {
				alert(e.message);
				chrome.tabs.getCurrent(function(tab) {
					chrome.tabs.remove(tab.id, function() {
						chrome.tabs.update(parseInt(params['tabId']), {selected:true});
					});
				});				
			}
		);
	});
	
	$('#button_save').click(function (e) {
		$('#button_save')[0].disabled = true;
		$('#button_save').text('Saving...');
		hyves.call('media.update', {'mediaid': mediaid, 'title': $('#field_name').val()}, function(response) {
			$('#button_save')[0].disabled = false;
			$('#button_save').text('Naam opslaan');
		});
	});

	$('#button_setprofilepicture').click(function (e) {
		$('#button_setprofilepicture')[0].disabled = true;
		$('#button_setprofilepicture').text('Setting profile picture...');
		hyves.call('users.updateMedia', {'mediaid': mediaid}, function(response) {
			$('#button_setprofilepicture').replaceWith('<span class="success">Profile picture is set</span>');
		});
	});
	$('#footercontent').append(share_content);
});


</script>
    <title>Foto uploaden...</title>
  </head>
<body>
<div id="canvas_wrapper"></div>
	<div id="page">
		<div id="page-hdr"><div class="donate"><a href="javascript:window.open('http://www.hyves-share.nl/button/pay/?member_id=770379','paywindow','toolbar=0,status=0,width=600,height=500,scrollbars=yes');" target="_blank">Doneer hier met Hyves!</a></div></div>
		<div id="page-con">
			<div id="page-con-hdr">
				<div class="box">
					<div id="page-con-info"><div class="bottom-inline-block"><h1>Chrome Foto Uploader</h1></div></div>
					<div class="box-con-bg"></div>
				</div>
				<div class="border"></div>
				<div class="bg"></div>
			</div>
			<div id="page-con-body">
				<div class="line wrapper w8">
					<div class="unit s1">
						<div class="box">
							<div class="box-hdr"><div class="box-hdr-bg">&nbsp;</div><div class="box-hdr-inner"><h2>Foto geupload!</h2></div></div>
							<div class="box-con"><div class="box-con-bg">&nbsp;</div>
								<div class="box-con-inner">
								
									<div id="wrapper_photo_upload">
										<h2>Code om op Hyves te gebruiken</h2>
										<table><tr><td>
										<div id="uploaded_image"></div>
										</td><td valign="top">
										<textarea id="field_fltag" readonly onfocus="this.select();"></textarea>
										</td></tr></table>
										<h2>Foto naam</h2>
										<input type="text" id="field_name" /><br>
										<button id="button_save"/>Naam opslaan</button><br>
										<h2>Voeg foto toe aan album</h2>
										<ul id="list_album">
										</ul>
										<h2>Selecteer als profielfoto</h2>
										<button id="button_setprofilepicture"/>Selecteer als profielfoto</button>
									</div>
		
								</div>
							</div>
						</div>
					</div>
					<div class="unit s2">
						<div class="box">
							<div class="box-hdr"><div class="box-hdr-bg">&nbsp;</div><div class="box-hdr-inner"><h2>Nieuwe foto albums?</h2></div></div>
							<div class="box-con"><div class="box-con-bg">&nbsp;</div>
								<div class="box-con-inner">
									Settings van de Chrome Foto Uploader aanpassen? Ga dan naar de <a href="options.html">settings pagina</a>.<br><br>Mocht je nieuwe albums hebben toegevoegd. Dan is een bezoek aan deze pagina of de settings pagina voldoende om deze te verversen binnen de Chrome Foto Uploader.
								</div>
							</div>
						</div>
						<div class="box">
							<div class="box-hdr"><div class="box-hdr-bg">&nbsp;</div><div class="box-hdr-inner"><h2>Andere Chrome extensies</h2></div></div>
							<div class="box-con"><div class="box-con-bg">&nbsp;</div>
								<div class="box-con-inner">
									<div id="wrapper_extensions_upload">
										<ul>
										<li><a href="https://chrome.google.com/webstore/detail/ddpfgdjnojbcmppcihoajinjknlcbjih" target="_blank">Hyves Respect Button</a></li>
										<li><a href="https://chrome.google.com/webstore/detail/peahcigdihdbbdpkkiihmccladcnacoh" target="_blank">Hyves Short-url</a></li>
										</ul>
									</div>
								</div>
							</div>
						</div>
					</div>					
				</div>
				<div class="border"></div>
				<div class="bg"></div>			
			</div>
			<div id="page-con-ftr">
				<div class="border"></div>
				<div class="bg"></div>		
			</div>
		</div>
		<div id="page-ftr">
			<div class="line">
					<div id="footercontent"></div>
			</div>
		</div>
	</div>
</body>
</html>